﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Qy.Core;
using Qy.Scenario;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Qy.Web.Authorize;

/// <summary>
/// 授权判断
/// </summary>
public class ActionPermissionFilter : ActionFilterAttribute//, IAsyncActionFilter
{
    public string Permission { get; set; }
    public ActionPermissionFilter() { }
    public ActionPermissionFilter(string permission)
    {
        Permission = permission;
    }

    /// <summary>
    /// 执行Action前校验是否有权限访问
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    /// <returns></returns>
    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        ILoginUserInfoMethods login = context.HttpContext.RequestServices.GetService<ILoginUserInfoMethods>();
        ILoginUserInfo userInfo = await login.LoginUserInfoAsync();
        MenuService menuList = context.HttpContext.RequestServices.GetService<MenuService>();
        List<Menu> menus = await menuList.GetAllAsync();
        Menu menuId = menus?.FirstOrDefault(m => m.RoleCode == Permission);
        int mid = menuId == null ? 0 : menuId.Id;
        if (userInfo.GroupId != 1 && !userInfo.SystemRole.Exists(x => x == mid))
        {
            JsonResult result = new(new { status = 0, msg = "没有权限操作此功能" })
            {
                ContentType = "application/json",
            };
            context.Result = result;
        }
        else
            await base.OnActionExecutionAsync(context, next);


    }
}
